package com.simin.mall.base;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;


import com.simin.base.appnet.netother.RxSubscriber;
import com.simin.base.appnet.progress.TokenListener;
import com.simin.base.apputils.EasyStatusBarUtil;
import com.simin.base.apputils.ToastUtils;
import com.simin.base.sqlite.DiskCacheManager;
import com.simin.mall.api.ApiResponse;
import com.simin.mall.api.listener.OnNetChangeListener;
import com.simin.mall.utils.ActivityUtil;
import com.simin.mall.utils.DoubleClickUtils;
import com.simin.mall.utils.StringUtils;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by wsm on 2024/9/9.
 * <p>
 */
public abstract class BaseActivity extends FragmentActivity implements TokenListener<ApiResponse>, OnNetChangeListener {
    public ActivityResultLauncher<Intent> register;//选择回调
    //rxjava
    public CompositeSubscription compositeSubscription = new CompositeSubscription();//管理所有的订阅

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initStatusBar();//初始化沉浸式“状态栏”
        initactivityResult();//初始化activity回调
        EasyStatusBarUtil.setStatusTextColor(true, this);
        initView(savedInstanceState);
        loadData();
    }

    protected abstract void initView(Bundle savedInstanceState);

    protected abstract void loadData();

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (null != this.getCurrentFocus()) {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            // 获得当前得到焦点的View，
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                //根据判断关闭软键盘
                InputMethodManager imm = (InputMethodManager) getSystemService(
                        Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 判断用户点击的区域是否是输入框
     *
     * @param v
     * @param event
     * @return
     */
    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 检测网络是否可用
     */
    public boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        return ni != null && ni.isConnectedOrConnecting();
    }

    /**
     * 设置不管用户调多大字体，app字体不变
     */

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.fontScale = 1;
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }


    /**
     * 设置头部状态栏
     */

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void initStatusBar() {
        //sdk 大于等于4.4的处理方式
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
            setStatusBarColor(); //设置状态栏的颜色
            //sdk 大于等于5.0的处理方式
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = getWindow();
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);//清除5.0 状态栏lin 的颜色
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);//设置该bar lin的背景色为透明

            }
        }

    }

    //设置sdk为4.4以上的沉浸式“状态栏”
    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    //设置状态栏的颜色
    public void setStatusBarColor() {
//        SystemBarTintManager tintManager = new SystemBarTintManager(this);
//        tintManager.setStatusBarTintEnabled(true);
//        tintManager.setStatusBarTintResource(R.drawable.bar_shape);//将状态栏设置为主题色
    }

    //设置状态栏字体颜色
    public void setStatusBarTextColor(boolean isDarkBackground) {
        View decor = getWindow().getDecorView();
        if (isDarkBackground) {
            //黑暗背景字体浅色
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        } else {
            //高亮背景字体深色
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }

    /**
     * @param visible
     */
    public void setNavigationBar(int visible) {
        View decorView = getWindow().getDecorView();
        //显示NavigationBar
        if (View.GONE == visible) {
            int option = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
            decorView.setSystemUiVisibility(option);
        }
    }


    /**
     * 设置全屏模式，并根据参数选择是否显示状态栏和导航栏
     *
     * @param isShowStatusBar     是否显示状态栏
     *                            true: 显示状态栏
     *                            false: 隐藏状态栏
     * @param isShowNavigationBar 是否显示导航栏
     *                            true: 显示导航栏
     *                            false: 隐藏导航栏
     */
    public void setFullscreen(boolean isShowStatusBar, boolean isShowNavigationBar) {
        int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
        if (!isShowStatusBar) {
            // 如果不显示状态栏，则设置为全屏模式
            uiOptions |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_FULLSCREEN;
        } else {
            // 保持状态栏可见但扩展到全屏
            uiOptions |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
        }
        if (!isShowNavigationBar) {
            // 如果不显示导航栏，则隐藏导航栏
            uiOptions |= View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
        } else {
            // 保持导航栏可见但扩展到全屏
            uiOptions |= View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
        }
        // 设置系统 UI 选项
        getWindow().getDecorView().setSystemUiVisibility(uiOptions);

    }

    /**
     * 自动关闭软键盘
     *
     * @param activity
     */
    public static void closeKeybord(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
        }
    }

    //初始化跳转Activity回调数据
    public void initactivityResult() {
        // 下一个Activity回退后 在此获取返回的值
        register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result != null) {
                    Intent intent = result.getData();
                    if (intent != null && result.getResultCode() == Activity.RESULT_OK) {
                        onActivityForResult(intent);
                    }
                }
            }
        });
    }

    //获取下一个activity回调数据
    public void onActivityForResult(Intent intent) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        detachCompositeSubscription();//取消所有的订阅
    }

    /**
     * 建立Composite订阅管理，取消所有订阅  rxjava中使用
     */
    public void detachCompositeSubscription() {
        if (compositeSubscription != null
                && compositeSubscription.hasSubscriptions()) {
            //取消注册，以避免内存泄露
            compositeSubscription.unsubscribe();
        }
    }


    protected <T> void addSubscription(Observable<T> observable, RxSubscriber<T> subscriber) {
        //管理所有的订阅
        compositeSubscription = new CompositeSubscription();
        compositeSubscription.add(observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(subscriber));
    }


    @Override
    public void onSuccess(ApiResponse data) {
        if (data.code == -1 || data.code == -2) {
            //-1 登录信息过期，请重新登录 -2其它设备登录
            ToastUtils.show(data.message);
//            ActivityUtil.finishAll(this, LoginActivity.class);
            //清除所有缓存信息
            DiskCacheManager.clearAll();
        }else if (data.code > 0 /*&& data.code < 500*/ && StringUtils.isNotBlank(data.message)) {//code小于500才显示错误信息
            ToastUtils.show(data.message);
        }
    }

    @Override
    public void onFailure(String code, String msg) {
        if (DoubleClickUtils.isFastDoubleClick()) {
            return;
        }
//        if ("500".compareTo(code) > 0) {//code小于500才显示错误信息
        ToastUtils.show(msg);
//        }
    }

    @Override
    public void onNetChange() {

    }
}
